package com.cscec81.passport.base.oauth2.server.authorization.customizer;

import com.cscec81.passport.base.oauth2.server.authorization.domain.PassportUser;
import com.cscec81.passport.base.oauth2.server.authorization.model.UserAuth;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;

import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public abstract class AbstractTokenCustomizer {
  public AbstractTokenCustomizer() {
  }

  protected void appendAll(Map<String, Object> attributes, Authentication authentication, Set<String> authorizedScopes) {
    this.appendAuthorities(attributes, authentication);
    this.appendCommons(attributes, authentication, authorizedScopes);
  }

  protected void appendAuthorities(Map<String, Object> attributes, Authentication authentication) {
    if (CollectionUtils.isNotEmpty(authentication.getAuthorities())) {
      Set<String> authorities = (Set)authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
      attributes.put("authorities", authorities);
    }
  }

  protected void appendCommons(Map<String, Object> attributes, Authentication authentication, Set<String> authorizedScopes) {
    if (CollectionUtils.isNotEmpty(authorizedScopes)) {
      attributes.put("scope", authorizedScopes);
    }

    if (authentication instanceof UsernamePasswordAuthenticationToken) {
      PassportUser principal = (PassportUser) authentication.getPrincipal();
      this.putUserInfo(attributes, principal);
      System.out.println("1");
    }

//    if (authentication instanceof OAuth2AccessTokenAuthenticationToken) {
//      Object details = authentication.getDetails();
//      if (ObjectUtils.isNotEmpty(details) && details instanceof UserAuth) {
//        UserAuth principal = (UserAuth)details;
//        this.putUserInfo(attributes, principal);
//      }
//    }
  }

  private void putUserInfo(Map<String, Object> attributes, PassportUser principal) {
    attributes.put("userId", principal.getUserId());
//    attributes.put("userCode", principal.getUserCode());
//    attributes.put("userCodeNew", principal.getUserCodeNew());
//    attributes.put("realName", principal.getRealName());
    attributes.put("username", principal.getUsername());
  }
}
